package org.devocean.groupbuying.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.devocean.groupbuying.dao.PaypalPaymentDAO;
import org.devocean.groupbuying.domain.PaypalPayment;

@Repository
public class PayPalPaymentDAOImpl implements PaypalPaymentDAO {

	@PersistenceContext
	private EntityManager em;
	@SuppressWarnings("unchecked")
	public List<PaypalPayment> findAllPaypalPayments() {
		return em.createQuery("select pp from PaypalPayment pp")
				.getResultList();
	}

	public void deletePaypalPayment(int id) {
		final PaypalPayment paypalPayment = em.find(PaypalPayment.class, id);

		if (paypalPayment != null) {
			em.remove(paypalPayment);
		}

	}

	public PaypalPayment savePaypalPayment(PaypalPayment paypalPayment) {
		em.persist(paypalPayment);
		return paypalPayment;
	}

	public PaypalPayment updatePaypalPayment(PaypalPayment paypalPayment) {
		return em.merge(paypalPayment);
	}

	public PaypalPayment findPaypalPaymentById(int id) {
		return em.find(PaypalPayment.class, id);
	}

	public long countPartner() {

		return em.createQuery("select count(pa) from PaypalPayment pa",
				long.class).getSingleResult();
	}

	public PaypalPayment findPaypalPaymentByPurchaseItemId(Integer id) {

		final Query query = em
				.createQuery("select pp from PaypalPayment pp where pp.payment.purchaseItemID=:piID");

		query.setParameter("piID", id);

		return (PaypalPayment) query.getResultList().get(0);
	}

}
